package com.kapcb.statemachine;

import com.kapcb.statemachine.exception.StateMachineException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <a>Title: StateMachineFactory </a>
 * <a>Author: Kapcb <a>
 * <a>Description: StateMachineFactory <a>
 *
 * @author Kapcb
 * @version 1.0
 * @date 2024/7/14 15:51
 * @since 1.0
 */
public class StateMachineFactory {

    /**
     * machineId
     */
    static Map<String, StateMachine<?, ?, ?>> stateMachineMap = new ConcurrentHashMap<>();

    /**
     * register state machine
     */
    public static <S, E, C> void register(StateMachine<S, E, C> stateMachine) {
        String machineId = stateMachine.getMachineId();
        if (stateMachineMap.get(machineId) != null) {
            throw new StateMachineException("The state machine with id [" + machineId + "] is already built, no need to build again");
        }
        stateMachineMap.put(stateMachine.getMachineId(), stateMachine);
    }

    /**
     * get state machine by machineId
     */
    public static <S, E, C> StateMachine<S, E, C> get(String machineId) {
        StateMachine stateMachine = stateMachineMap.get(machineId);
        if (stateMachine == null) {
            throw new StateMachineException("There is no stateMachine instance for " + machineId + ", please build it first");
        }
        return stateMachine;
    }
}
